import { getPool } from '../config/database';

interface Role {
  id?: number;
  name: string;
  permissions: string;
}

interface UserRole {
  userId: number;
  roleId: number;
}

export class RolesModel {
  /**
   * 获取所有角色
   */
  static async findAll(): Promise<Role[]> {
    const pool = getPool();
    const [rows] = await pool.query('SELECT * FROM roles');
    return rows as Role[];
  }

  /**
   * 通过ID获取角色
   */
  static async findById(id: number): Promise<Role | null> {
    const pool = getPool();
    const [rows] = await pool.query('SELECT * FROM roles WHERE id = ?', [id]);
    const roles = rows as Role[];
    return roles.length ? roles[0] : null;
  }

  /**
   * 创建角色
   */
  static async create(role: Omit<Role, 'id'>): Promise<number> {
    const pool = getPool();
    const [result] = await pool.query(
      'INSERT INTO roles (name, permissions) VALUES (?, ?)',
      [role.name, role.permissions]
    );
    return (result as any).insertId;
  }

  /**
   * 为用户分配角色
   */
  static async assignRole(userId: number, roleId: number): Promise<boolean> {
    const pool = getPool();
    const [result] = await pool.query(
      'INSERT INTO user_roles (userId, roleId) VALUES (?, ?)',
      [userId, roleId]
    );
    return (result as any).affectedRows > 0;
  }

  /**
   * 获取用户的角色
   */
  static async getUserRoles(userId: number): Promise<Role[]> {
    const pool = getPool();
    const [rows] = await pool.query(
      `SELECT r.* FROM roles r 
       JOIN user_roles ur ON r.id = ur.roleId 
       WHERE ur.userId = ?`,
      [userId]
    );
    return rows as Role[];
  }
}
